#!/bin/bash

# 构建交叉编译器gcc
# Building GCC requires GMP 4.2+, MPFR 2.4.0+ and MPC 0.8.0+
sudo apt -y install build-essential texinfo dosfstools mtools nasm
sudo apt install libgmp-dev libmpfr-dev libmpc-dev -y
sudo apt install grub-pc -y

export PREFIX="/usr/local/i686elfgcc"
export TARGET=i686-elf
export PATH="$PREFIX/bin:$PATH"

mkdir /tmp/src
cd /tmp/src
curl -O https://mirrors.aliyun.com/gnu/binutils/binutils-2.40.tar.xz # If the link 404's, look for a more recent version
tar xf binutils-2.40.tar.xz
mkdir binutils-build
cd binutils-build
../binutils-2.40/configure --target=$TARGET --with-sysroot --enable-interwork --enable-multilib --disable-nls --disable-werror --prefix=$PREFIX 2>&1 | tee configure.log
make all install 2>&1 | tee make.log


cd /tmp/src
curl -O https://mirrors.aliyun.com/gnu/gcc/gcc-13.2.0/gcc-13.2.0.tar.xz
tar xf gcc-13.2.0.tar.xz
mkdir gcc-build
cd gcc-build
../gcc-13.2.0/configure --target=$TARGET --prefix="$PREFIX" --disable-nls --enable-languages=c,c++ --without-headers
make all-gcc -j$(nproc) 2>&1 | tee make.log
make all-target-libgcc -j$(nproc) 2>&1 | tee make1.log
make install-gcc 
make install-target-libgcc 

cd /tmp/src
curl -O https://mirrors.tuna.tsinghua.edu.cn/gnu/gdb/gdb-14.2.tar.gz
tar xf gdb-14.2.tar.gz
mkdir gdb-build
cd gdb-build
../gdb-14.2/configure --target="$TARGET" --prefix="$PREFIX" --program-prefix=i686-elf-
make -j$(nproc)
make install



# qemu
# 开一个干净的子 shell，完全丢掉 Snap 相关的环境变量
env -i \
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \
  LD_LIBRARY_PATH="" \
  DISPLAY=":1" \
  XDG_SESSION_TYPE="x11" \
  bash --norc --noprofile
